#include <stdio.h>
#include "3calc.h"

int len(char stack[]) {
	int length = 0;

	while (stack[length] != '\0')
	{
		length++;
	}
	return length;
}

int len(int stack[]) {
	int length = 0;

	while (stack[length] != '\0')
	{
		length++;
	}
	return length;
}

int len(double stack[]) {
	int length = 0;

	while (stack[length] != '\0')
	{
		length++;
	}
	return length;
}

int transformOpToNumber(char op) {
	switch (op)
	{
	case '*':
		return 60;
	case '/':
		return 61;
	case '+':
		return 40;
	case '-':
		return 41;
	default:
		break;
	}
}

void handleOperator(char opStack[], char op, double values[]) {
	int opStackLength = len(opStack);

	if (op == '+' || op == '-' || op == '*' || op == '/') {
		if (!opStackLength) {
			push(opStack, op);
		}
		else if (opStack[opStackLength - 1] == '(') {
			push(opStack, op);
		}
		else {
			char opStackTop = opStack[opStackLength - 1];
			int opGap = transformOpToNumber(op) - transformOpToNumber(opStackTop);

			while (opGap <= 10)
			{
				opStackTop = pop(opStack);
				computed(opStackTop, values);

				if (!len(opStack)) break;

				opStackTop = opStack[len(opStack) - 1];
				opGap = transformOpToNumber(op) - transformOpToNumber(opStackTop);
			}
			push(opStack, op);
		}
	}
	else if (op == '(') {
		push(opStack, op);
	}
	else if (op == ')') {
		char opStackTop = pop(opStack);

		while (opStackTop && opStackTop != '(') {
			computed(opStackTop, values);
			opStackTop = pop(opStack);
		}
	}
}

void computed(char op, double values[]) {
	double n2 = pop(values);
	double n1 = pop(values);
	double rel = 0.0;

	if (op == '+') {
		rel = n1 + n2;
	}
	else if (op == '-') {
		rel = n1 - n2;
	}
	else if (op == '*') {
		rel = n1 * n2;
	}
	else if (op == '/') {
		if (n2 != 0) {
			rel = n1 / n2;
		}
		else {
			printf("Zero is not a multiplier!");
		}
	}
	push(values, rel);
}